﻿/**
 * 通用js方法封装处理
 */
import { getToken } from '@/utils/auth'
import defaultSettings from '@/settings'
import { debounce, cloneDeep, isNull, isNumber, isObject } from 'lodash-es'

const baseURL = import.meta.env.VITE_APP_BASE_API

// 防抖动包装器
export function debounceWrapper(fn: any) {
  return debounce(fn, 200)
}

// 日期格式化
export function parseTime(time: any, pattern: any) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: any, key: any) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 表单重置
export function resetForm(refName: any) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

// 表单重置vue3版
export function resetFormPlus(ref: any) {
  if (ref) {
    ref.resetFields()
  }
}

// 添加创建日期范围
export function addDateRange(params: any, propRange: any, dateRange: any) {
  const search = cloneDeep(params)
  if (null != propRange && '' != propRange && null != dateRange && '' != dateRange) {
    search.params = {}
    if (propRange.length > dateRange.length) {
      dateRange.forEach((item: any, index: any, array: any) => {
        search[propRange[index]] = dateRange[index]
        search.params[propRange[index]] = dateRange[index]
      })
    } else {
      propRange.forEach((item: any, index: any, array: any) => {
        search[propRange[index]] = dateRange[index]
        search.params[propRange[index]] = dateRange[index]
      })
    }
  }
  return search
}

// 回显数据字典
export function selectDictLabel(datas: any, value: any) {
  const actions: Array<any> = []
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue == '' + value) {
      actions.push(datas[key].dictLabel)
      return true
    }
  })
  return actions.length > 0 ? actions.join('') : value
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas: any, value: any, separator: any) {
  const actions: Array<any> = []
  const currentSeparator = undefined === separator ? ',' : separator
  const temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue == '' + temp[val]) {
        actions.push(datas[key].dictLabel + currentSeparator)
      }
    })
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

// 通用下载方法
export function download(fileName: any) {
  window.location.href =
    baseURL + '/common/download?fileName=' + encodeURI(fileName) + '&delete=' + true
}

/**
 * 从URL下载文件 使用form下载文件 post表单提交
 * @param {String} url
 */
export function downloadUrl(url: any, query: any) {
  let newUrl = url
  if (newUrl.startsWith('http://') || url.startsWith('https://')) {
    newUrl = newUrl
  } else if (url.startsWith('/')) {
    newUrl = baseURL + newUrl
  } else {
    newUrl = baseURL + '/' + newUrl
  }
  const elemform = document.createElement('form')
  elemform.action = newUrl
  elemform.target = '_blank'
  elemform.method = 'post'
  // 认证Token
  const elemInput = document.createElement('input')
  elemInput.type = 'hidden'
  elemInput.setAttribute('name', defaultSettings.tokenName)
  elemInput.setAttribute('value', getToken())
  elemform.appendChild(elemInput)

  if (query) {
    for (const k in query) {
      if (query[k] !== undefined) {
        if (isObject(query[k])) {
          for (const k1 in query[k]) {
            const elemInput = document.createElement('input')
            elemInput.type = 'hidden'
            elemInput.setAttribute('name', k + '[' + k1 + ']')
            elemInput.setAttribute('value', query[k][k1])
            elemform.appendChild(elemInput)
          }
        } else {
          const elemInput = document.createElement('input')
          ;(elemInput.type = 'hidden'), elemInput.setAttribute('name', k)
          elemInput.setAttribute('value', query[k])
          elemform.appendChild(elemInput)
        }
      }
    }
  }
  document.body.appendChild(elemform)
  console.log('elemform5',elemform)
  elemform.submit()
  document.body.removeChild(elemform)
}

// 字符串格式化(%s )
export function sprintf(str: any) {
  // eslint-disable-next-line prefer-rest-params
  const args = arguments
  let flag = true,
    i = 1
  str = str.replace(/%s/g, function () {
    const arg = args[i++]
    if (typeof arg === 'undefined') {
      flag = false
      return ''
    }
    return arg
  })
  return flag ? str : ''
}

/**
 * 是否为空
 * @param obj
 * @returns {boolean}
 */
export function isEmpty(obj: any) {
  return typeof obj === 'undefined' || obj === null || obj === ''
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str: any) {
  if (!str || str == 'undefined' || str == 'null') {
    return ''
  }
  return str
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data: any, id: any, parentId: any, children: any, rootId: any) {
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId =
    rootId ||
    // eslint-disable-next-line prefer-spread
    Math.min.apply(
      Math,
      data.map((item: any) => {
        return item[parentId]
      })
    ) ||
    0
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  //循环所有项
  const treeData = cloneData.filter((father: any) => {
    const branchArr = cloneData.filter((child: Array<any>) => {
      //返回每一项的子级数组
      return father[id] === child[parentId]
    })
    branchArr.length > 0 ? (father.children = branchArr) : ''
    //返回第一层
    return father[parentId] === rootId
  })
  return treeData != '' ? treeData : data
}

/**
 * 构建扩展字段数组
 * @param {Number} count 扩展字段个数
 */
export function buildExtColNames(count: any) {
  const extColName = []
  for (let index = 1; index <= count; index++) {
    extColName.push({
      enabled: false,
      extcolName: 'extcol' + index,
      extcolLabel: '',
      extcolAlias: ''
    })
  }
  return extColName
}

/**
 * 千分位数值
 * @param {数字格式化} value
 * @param {小数位，默认3} precision
 */
export function formatNumber(value: any, precision: any) {
  if (isNull(value) || !isNumber(value)) {
    return value
  }
  if (typeof value === 'string') {
    value = Number(value)
  }
  let options
  if (isEmpty(precision)) {
    options = {}
  } else {
    options = {
      maximumFractionDigits: precision,
      minimumFractionDigits: precision
    }
  }
  return value.toLocaleString('zh', options)
}

/**
 * 格式化金额（人民币）
 * @param {金额} value
 * @param {小数位，默认2} precision
 * @returns {string|*}
 */
export function formatMoney(value: any, precision: any) {
  if ((!value && value !== 0) || isNaN(value)) {
    return value
  }
  if (typeof value === 'string') {
    value = Number(value)
  }
  if (isEmpty(precision)) {
    precision = 2
  }
  return value.toLocaleString('zh', {
    style: 'currency',
    currency: 'CNY',
    maximumFractionDigits: precision,
    minimumFractionDigits: precision
  })
  // if (value.toString().indexOf('.') === -1) {
  // 	return value.toLocaleString() + '.00';
  // }
  // return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}

/**
 * 格式化百分比
 * @param {小数} value
 * @returns
 */
export function formatPercent(value: any) {
  if (typeof value === 'string') {
    value = Number(value)
  }
  return value.toLocaleString('zh', {
    style: 'percent',
    useGrouping: false
  })
}

/**
 * 格式化日期
 * @param value
 * @returns {string|*}
 */
export function formatDate(value: any) {
  if (!value) {
    return value || ''
  }
  const date = new Date(value.replace(/-/g, '/'))
  return date
    .toLocaleString('zh', {
      timeZone: 'Asia/Shanghai',
      hour12: false
    })
    .replace(/\//g, '-')
    .replace(' 24:', ' 00:')
    .replace(' 00:00:00', '')
}

/**
 * 格式化文件大小
 * @param fileObj
 * @returns {string}
 */
export function formatFileSize(fileObj: any) {
  const fileSize = fileObj.fileSize
  if (fileSize < 1024) {
    return fileSize + 'B'
  } else if (fileSize < 1024 * 1024) {
    let temp: any = fileSize / 1024
    temp = temp.toFixed(2)
    return temp + 'KB'
  } else if (fileSize < 1024 * 1024 * 1024) {
    let temp: any = fileSize / (1024 * 1024)
    temp = temp.toFixed(2)
    return temp + 'MB'
  } else {
    let temp: any = fileSize / (1024 * 1024 * 1024)
    temp = temp.toFixed(2)
    return temp + 'GB'
  }
}

/**
 * 静态文件资源路径处理
 * @param url
 * @returns {string}
 */
export function getAssetsUrl(url: string): string {
  return new URL(url, import.meta.url).href
}

/**
 * 生成指定长度的随机字符串
 * @param len
 * @returns {string}
 */
export function randomString(len: number): string {
  len = len || 32
  const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  const maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

/**
 * 判断字符串是否为base64字符串
 * @param str
 * @returns {boolean}
 */
export const isBase64 = function(str: string): boolean {
  try {
      return !!atob(str); // 对于浏览器环境
  } catch (err) {
      return false;
  }
}

// 处理平台上传接口的返回值
export const getCustomUploadTrans = function (data: any) {
  const { fileType, url, fileName, storageType } = data
  let resObj = {}
  if (storageType == 'local' || storageType == 'ftp') {
    const myUrl = location.origin + import.meta.env.VITE_APP_BASE_API + '/custom' + url
    resObj = {
      fileName,
      url: myUrl,
      fileType,
      storageType,
      type: fileType
    }
  } else if (storageType == 'fdfs') {
    resObj = {
      fileName,
      url,
      fileType,
      storageType,
      type: fileType
    }
  }

  return resObj
}

const anvilUtil = {
  parseTime,
  resetForm,
  addDateRange,
  selectDictLabel,
  selectDictLabels,
  download,
  downloadUrl,
  handleTree,
  formatNumber,
  formatMoney,
  formatPercent,
  formatDate,
  getAssetsUrl,
  randomString,
  getCustomUploadTrans,
  isBase64
}

export default anvilUtil
